package com.lc.cehui.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.cehui.R;
import com.lc.cehui.app.AppActivity;
import com.lc.cehui.http.glide.GlideApp;
import com.lc.cehui.http.request.CarDelaApi;
import com.lc.cehui.http.request.CarYsApi;
import com.lc.cehui.http.request.PassUserIdAPI;
import com.lc.cehui.http.response.BaseBean;
import com.lc.cehui.http.response.ShopCarBean;
import com.lc.cehui.other.IntentKey;
import com.lc.cehui.util.SPUtil;
import com.lc.cehui.util.SuperUtil;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShoppingCartActivity extends AppActivity {

    @BindView(R.id.tv_anditem)
    TextView tvAnditem;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.cb_all)
    CheckBox cbAll;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_js)
    TextView tvJs;
    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.srl)
    SmartRefreshLayout srl;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    private BaseQuickAdapter shoppingCarAdapter;
    private BaseQuickAdapter shoppingCarItemAdapter;
    private List<ShopCarBean.DataBean> list_data;
    private List<ShopCarBean.DataBean.GoodsBean> list_goods;
    private List<ShopCarBean.DataBean.GoodsBean> list_all_goods;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shopping_cart;
    }


    private boolean manage = true;//编辑状态

    @Override
    protected void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(ShoppingCartActivity.this));
        srl.setRefreshHeader(new MaterialHeader(ShoppingCartActivity.this));
        srl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srl.finishRefresh();
            }
        });
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {
                if (manage) {
                    manage = false;
                    titleBar.setRightTitle("完成");
                    tvJs.setText("删除");
                } else {
                    manage = true;
                    titleBar.setRightTitle("管理");
                    tvJs.setText("结算");
                }
            }
        });

        recyclerView.setAdapter(shoppingCarAdapter = new BaseQuickAdapter<ShopCarBean.DataBean, BaseViewHolder>(R.layout.adapter_shopcar, list_data) {
            @Override
            protected void convert(@NonNull BaseViewHolder holder, ShopCarBean.DataBean dataBean) {
                RecyclerView recyclerView = holder.getView(R.id.recyclerView);
                recyclerView.setLayoutManager(new LinearLayoutManager(ShoppingCartActivity.this));
                holder.setText(R.id.shopname_tv, dataBean.getName());
                CheckBox checkBox = holder.getView(R.id.check_cb);
                checkBox.setOnClickListener(v -> {
                    for (int i = 0; i < list_all_goods.size(); i++) {
                        list_all_goods.get(i).setSelected(checkBox.isChecked());
                    }
                    shoppingCarItemAdapter.notifyDataSetChanged();
                });
                recyclerView.setAdapter(shoppingCarItemAdapter = new BaseQuickAdapter<ShopCarBean.DataBean.GoodsBean, BaseViewHolder>(R.layout.adapter_shopcar_item, list_goods) {
                    @Override
                    protected void convert(@NonNull BaseViewHolder holder, ShopCarBean.DataBean.GoodsBean goodsBean) {
                        GlideApp.with(ShoppingCartActivity.this).load(goodsBean.getPrice()).into((ImageView) holder.getView(R.id.iv_logo));
                        holder.setText(R.id.tv_name, goodsBean.getName()).setText(R.id.tv_money, "￥" + goodsBean.getPrice())
                                .setText(R.id.etAmount, goodsBean.getNum() + "")
                                .setText(R.id.textView2, goodsBean.getAttr());
                        CheckBox checkBox = holder.getView(R.id.checkBox);
                        checkBox.setOnClickListener(view -> {
                            goodsBean.setSelected(checkBox.isChecked());
                            CalculatedAmount();
                        });
                        holder.getView(R.id.btnIncrease).setOnClickListener(view -> {//加
                            CarYs(goodsBean, 1, holder.getAbsoluteAdapterPosition());
                        });
                        holder.getView(R.id.btnDecrease).setOnClickListener(view -> {//减
                            CarYs(goodsBean, 2, holder.getAbsoluteAdapterPosition());
                        });
                    }
                });
                shoppingCarItemAdapter.setNewInstance(dataBean.getGoods());

            }
        });
        showLoadView(shoppingCarAdapter);
    }

    private boolean isFirst;

    @Override
    protected void initData() {
        EasyHttp.post(this)
                .api(new PassUserIdAPI("api/goods_car"))
                .request(new HttpCallback<ShopCarBean>(this) {
                    @Override
                    public void onSucceed(ShopCarBean data) {
                        //ShopCarBean data = JSON.parseObject(ResourceUtils.readAssets2String("json.json"),ShopCarBean.class);
                        if (data.getData().size() != 0) {
                            tvMoney.setText(SuperUtil.changTVsize("0.00"));
                            SuperUtil.setVisibility(ll1,true);
                            list_all_goods = new ArrayList<>();
                            list_data = new ArrayList<>();
                            list_data = data.getData();
                            LogUtils.e(JSON.toJSONString(data.getData()));
                            for (int i = 0; i < data.getData().size(); i++) {
                                list_all_goods.addAll(data.getData().get(i).getGoods());
                            }
                            LogUtils.e(JSON.toJSONString(list_all_goods));
                            tvAnditem.setText("共有" + list_all_goods.size() + "件商品");
                            shoppingCarAdapter.setNewInstance(list_data);
                        } else {
                            showEmptyView(shoppingCarAdapter);
                        }
                    }
                });
    }

    @OnClick({R.id.cb_all, R.id.tv_js})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cb_all:

                break;
            case R.id.tv_js:
                if (manage) {

                } else {
                    del();
                }

                break;
        }
    }

    private void CalculatedAmount() {
        int money = 0;
        for (int i = 0; i < list_all_goods.size(); i++) {
            if (list_all_goods.get(i).isSelected()){
                money = (Integer.parseInt(list_all_goods.get(i).getPrice())*list_all_goods.get(i).getNum()) + money;
            }
        }
        tvMoney.setText(SuperUtil.changTVsize(money+""));
    }


    private void del() {
        EasyHttp.post(this)
                .api(new CarDelaApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID, 0))
                        .setId("")
                ).request(new HttpCallback<BaseBean>(this) {
            @Override
            public void onSucceed(BaseBean data) {
                ToastUtils.showShort(data.getMsg());
            }
        });
    }

    private void CarYs(ShopCarBean.DataBean.GoodsBean goodsBean, int type, int pos) {
        EasyHttp.post(this)
                .api(new CarYsApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID, 0))
                        .setId(goodsBean.getCar_id()).setType(type)
                ).request(new HttpCallback<BaseBean>(this) {
            @Override
            public void onSucceed(BaseBean data) {
                if (callBackCode(data)) {
                    if (type == 1) {
                        goodsBean.setNum(goodsBean.getNum() + 1);
                    } else {
                        goodsBean.setNum(goodsBean.getNum() - 1);
                    }
                    shoppingCarItemAdapter.notifyItemChanged(pos);
                }
                ToastUtils.showShort(data.getMsg());
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}